import json
from functools import wraps

from flask import request

try:
    from types import SimpleNamespace as Namespace
except ImportError:
    # Python 2.x fallback
    from argparse import Namespace

"""
request body decorator
类似于 SpringMVC 中的 @RequestBody

Copyright (C) chengpeng.hu. All Rights Reserved

@Author : chengpeng.hu
@Date : 2024
"""


def request_body(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        if request.method == 'POST':
            data = request.get_json(force=True)
            obj = json.loads(json.dumps(data), object_hook=lambda d: Namespace(**d))
            request.body = obj
        return func(*args, **kwargs)

    return wrapper
